package vn.ugame.controller;

import java.io.IOException;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import vn.ugame.processor.Processor;
import vn.ugame.processor.ProcessorManager;
import vn.ugame.utility.Security;

public class ServiceServlet extends GenericServlet {

    @Override
    public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        String requestURL = request.getRequestURI();
        String token = requestURL.replaceAll("/", "");
        String key = request.getParameter("key");
        
        String secretKey = Security.getInstance().createFirstSecretKey(key);        
        String serviceName = Security.getInstance().decrypt(token, secretKey);
        
        if(serviceName == null){
            secretKey = Security.getInstance().createSecondSecretKey(key);
            serviceName = Security.getInstance().decrypt(token, secretKey);
        }

        if (serviceName == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        
        request.setAttribute("secretKey", secretKey);

        ProcessorManager manager = ProcessorManager.getInstance();
        try {
            Processor processor = manager.createProcessor(serviceName);
            processor.process(request, response);
        } catch (Exception ex) {
            ex.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}
